package com.sky.chapter3.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 *
 * callable  必须先 用一个线程 对象来start ,  start 之后 才能借助 FutureTask 来获取返回的结果;
 *
 *
 */
public class CallableTest {


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // new Thread(new Runnable()).start();
        // new Thread(new FutureTask<V>()).start();
        // new Thread(new FutureTask<V>( Callable )).start();
        new Thread().start(); // 怎么启动Callable

        MyThread threadImpl = new MyThread();
        FutureTask<Integer> futureTask = new FutureTask<>(threadImpl); // 适配类

        new Thread(futureTask, "A").start();
        new Thread(futureTask, "B").start(); // 结果会被缓存，效率高

        Integer o = futureTask.get(); // mark 这个get 方法可能会产生阻塞！把他放到最后 或者使用异步通信来处理！
        System.out.println(o);


        FutureTask<Integer> futureTask1 = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() {
                System.out.println("内部类的方式实现 callable ");
                return 1023;
            }
        });
        new Thread(futureTask1).start();

        Integer integer = futureTask1.get();
        System.out.println(integer);


        FutureTask<Integer> futureTask2 = new FutureTask<>(() -> {

            System.out.println("lambda的方式实现 callable");
            return 1022;
        });

        new Thread(futureTask2).start();
        System.out.println(futureTask2.get());  //mark  线程必须先去执行, 才能够获取线程运行返回的值


    }

    static class MyThread implements Callable<Integer> {

        @Override
        public Integer call() {
            System.out.println("实现类的方式实现 callable "); // 会打印几个call
            // 耗时的操作
            return 1024;
        }

    }

}

